﻿using Ldt.DataEngine.DataFlowParse.Model;
using LDT.CoreLibrary;
using LdtDataEngin.ModuleDetail.BaseModule.Optimization;
using LdtJudge.DataEngine.CallInterface.ConfiCenter;
using LdtJudge.DataEngine.Common;
using LdtJudge.DataEngine.Common.CommHelp;
using LdtJudge.DataEngine.Common.ConfigXmlLoad;
using LdtJudge.DataEngine.Common.XmlUtility;
using LdtJudge.DataEngine.Data.DataParseStorage;
using LdtJudge.DataEngine.DataBaseStores;
using LdtJudge.DataEngine.Model.Collection;
using LdtJudge.DataEngine.Model.CommModel;
using LdtJudge.DataEngine.Model.DataModel.DataParseStorage;
using LdtJudge.DataEngine.Model.DataModel.SysCommon;
using LdtJudge.DataEngine.Model.EvidenceDerivation;
using LdtJudge.DataEngine.Model.EvidenceFact;
using LdtJudge.DataEngine.Model.XMLConfigModel.DataStores;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Xml;
using System.Xml.Linq;

namespace LdtDataEngin.ModuleDetail.CommonModule.PersonOptimize
{
    /// <summary>
    /// 案由分人员要素优选
    /// </summary>
    public class MoudlePersonOptimizeDetail : BaseModule.Optimization.OptimizationBase
    {
        /// 案由集合
        ///</summary> 
        private List<CaseCauseModel> CaseCausesList { get; }

        /// <summary>
        /// 文书在案件要素中心中的定位配置
        /// </summary>
        private List<DOCLocationModel> locationModelList { get; set; }

        /// <summary>
        /// 实例化构造函数
        /// </summary>
        /// <param name="dataContextIn">上下文数据</param>
        /// <param name="moudleName">模块名称</param>
        public MoudlePersonOptimizeDetail(DataContext dataContextIn, string moudleName)
        {
            base.dataContext = dataContextIn;
            CaseCausesList = dataContext.DataCommon.CaseCausesList;
            base.ModuleName = moudleName;
            var configModel = base.dataContext.DataLayerSys.GetConfigModel(moudleName);
            if (configModel.ConfigDetail != null)
            {
                if (dataContext.DataLayerOpt.SourdatModleList == null || dataContext.DataLayerOpt.SourdatModleList.Count == 0)
                {
                    dataContext.InteractiveShow.LogShow("进入案件优选结果补充程序");
                    DAL_An_anjiancunchu anjiancunchudal = new DAL_An_anjiancunchu();
                    var anjiancunchuList = anjiancunchudal.GetList(dataContext.DataLayerOpt.CaseId, "3");
                    if (anjiancunchuList.Count > 0)
                    {
                        DataSoursModel dataSoursModels = GetDataSoursModel(ReadDataXML(anjiancunchuList[0].Wenjianid));
                        dataContext.DataLayerOpt.SourdatModleList = dataSoursModels.dataModelList;
                        dataContext.DataLayerOpt.OptimizationXml = XmlUtility.DataModelByXml(dataContext.DataLayerOpt.SourdatModleList);
                    }
                }
                foreach (ConfigModel item in configModel.ConfigDetail)
                {

                    if (item.ExecuteType == "xml_var" && item.Code == "causeoptimize")
                    {
                        if (!string.IsNullOrWhiteSpace(item.FilePath))
                        {
                            string url = item.FilePath.Replace("{casetype}", dataContext.DataLayerOpt.CaseType).Replace("{causecode}", dataContext.DataLayerAns.CaseCausesList[0].CC_ID).ToLower().Replace(" ", "");//dataContext.DataLayerAns.CaseCausesList[0].CC_ID
                            Dictionary<string, string> dicElement = new Dictionary<string, string>();
                            dicElement.Add("fileFullName", url);
                            string elementMessage = WebUtil.DoGet(ConfigRetrieval.GetConfigRetrieval.GetAppSettingString("systemapi") + "/api/WordParse/GetConfigFileContent", dicElement, "utf-8");//ConfigRetrieval.GetConfigRetrieval.GetAppSettingString("systemapi")
                            dynamic elementcofig = JsonConvert.DeserializeObject<dynamic>(elementMessage);
                            if (elementcofig.result.code.ToString() == "1")
                            {
                                string elementcofigstr = elementcofig.body;
                                OptimizeElement = XmlUtility.DeserializeToObject<OptimizeElementConfig>(elementcofigstr);
                                OptimizeSourceSerializable optimizeSource = new OptimizeSourceSerializable();
                                dataContext.DataLayerSys.optimizeFactConfig = optimizeSource.OptimizeCommonSourceContxt(elementcofigstr);
                            }
                        }
                    }
                }
                var docmergeoptconfig = configModel.ConfigDetail.FirstOrDefault(a => a.Code.ToLower() == "docmergeopt");
                if (docmergeoptconfig != null && !string.IsNullOrWhiteSpace(docmergeoptconfig.ConfigContent))
                {
                    docmergeopt = docmergeoptconfig.ConfigContent;
                }

                var multipledocjudgeconfig = configModel.ConfigDetail.FirstOrDefault(a => a.Code.ToLower() == "multipledocjudge");
                if (multipledocjudgeconfig != null && !string.IsNullOrWhiteSpace(multipledocjudgeconfig.ConfigContent))
                {
                    multipledocjudge = multipledocjudgeconfig.ConfigContent;
                }

                string causeLocalContent = string.Empty;
                string causeStageContent = string.Empty;
                ConfigModel causeLocalConfig = configModel.ConfigDetail.FirstOrDefault(x => x.ExecuteCode == "elementpath.xml");
                if (causeLocalConfig != null)
                    causeLocalContent = causeLocalConfig.ConfigContent;
                ConfigModel causeStageConfig = configModel.ConfigDetail.FirstOrDefault(x => x.Code.ToLower() == "causestagelocation");
                if (causeStageConfig != null)
                    causeStageContent = causeStageConfig.ConfigContent;
                locationModelList = GetLocationModels(causeLocalContent, causeStageContent);
                dataContext.DataLayerSys.locationModelList = locationModelList;


            }
        }


        /// <summary>
        /// 加载数据
        /// </summary>
        /// <returns></returns>
        private (Dictionary<string, List<DataModel>> optmos, Dictionary<string, List<DataModel>> ansmos) LoadData()
        {
            Dictionary<string, List<DataModel>> listOptModels = new Dictionary<string, List<DataModel>>();
            Dictionary<string, List<DataModel>> listAnsModels = new Dictionary<string, List<DataModel>>();

            //获取案件优选存储的数据
            if (dataContext.DataLayerOpt.ElementAnalsisDataModelResults != null && dataContext.DataLayerOpt.ElementAnalsisDataModelResults.Count > 0)
            {
                listOptModels.Add(dataContext.DataLayerAns.CaseCausesList[0].CC_ID, dataContext.DataLayerOpt.ElementAnalsisDataModelResults);
            }
            else
            {
                try
                {
                    listAnsModels = dataContext.DataLayerAns.ElementAnalsisDataModelResults;
                    DAL_An_anjiancunchu anjiancunchudal = new DAL_An_anjiancunchu();
                    An_anjiancunchu anjiananyoucunchu = anjiancunchudal.GetList(base.dataContext.DataCommon.CaseId, "2").FirstOrDefault();
                    if (anjiananyoucunchu != null)
                    {
                        var anjianList = anjiancunchudal.GetList(base.dataContext.DataCommon.CaseId, "2").ToList();
                        foreach (var anj in anjianList)
                        {
                            DataSoursModel dataSoursModelOP = GetDataSoursModel(ReadDataXML(anj.Wenjianid));
                            string causeId = anj.Anyouid;
                            if (dataContext.DataCommon.CausePointDic != null && dataContext.DataCommon.CausePointDic.ContainsKey(anj.Anyouid))
                                causeId = dataContext.DataCommon.CausePointDic[anj.Anyouid];
                            listOptModels.Add(causeId, dataSoursModelOP.dataModelList.Select(item => item.Clone()).ToList());
                        }
                    }
                }
                catch (Exception ex)
                {
                    dataContext.InteractiveShow.LogShow("案由要素结果库，初始化失败，直接使用分析结果");
                }
            }
            return (listOptModels, listAnsModels);
        }
        /// <summary>
        /// 接口属性转换
        /// </summary>
        /// <param name="dataList">需要处理的数据源</param>
        private void FromatNodeList(List<DataModel> dataList)
        {
            if (dataList.Count > 0)
            {
                if (dataList.FirstOrDefault(a => a.sourceData.sourceList.FirstOrDefault(b => b.SourceCode.ToLower() == dataContext.DataCommon.SourceCode.ToLower()) != null) != null)
                {
                    List<DataModel> datamodeNodeList = dataList.Where(a => a.sourceData.sourceList.FirstOrDefault(b => b.SourceCode.ToLower() == dataContext.DataCommon.SourceCode.ToLower()) != null).ToList();
                    foreach (DataModel dataModelNode in datamodeNodeList)
                    {
                        if (dataModelNode.AttributesList != null)
                        {
                            foreach (AttributeInfo attributemodel in dataModelNode.AttributesList)
                            {

                                try
                                {
                                    Source attrSource = attributemodel.sourceList.FirstOrDefault(a => a.SourceCode.ToLower() == dataContext.DataLayerAns.SourceCode.ToLower());
                                    if (attrSource != null)
                                    {
                                        attrSource.AnalysisStatus = "0";
                                    }
                                }
                                catch (Exception ex)
                                {


                                }
                            }
                            Source nodeSoure = dataModelNode.sourceData.sourceList.FirstOrDefault(a => a.SourceCode.ToLower() == dataContext.DataCommon.SourceCode.ToLower());

                            if (nodeSoure != null)
                            {
                                nodeSoure.AnalysisStatus = "0";
                            }
                        }

                    }
                }
            }
        }
        /// <summary>
        /// xml转数据对象集合
        /// </summary>
        /// <param name="xmlStr"></param>
        /// <returns></returns>
        private List<DOCLocationModel> GetLocationModels(string causeLocalXml, string causeStageXml)
        {
            List<CTLocationModel> cTLocations = new List<CTLocationModel>();
            ParseLocationConfig locationConfigM = new ParseLocationConfig();
            var locationModels = locationConfigM.GetLocationModel(causeLocalXml, causeStageXml, dataContext.DataLayerOpt.OptimizationXml, dataContext.DataLayerAns.CaseType, dataContext.DataLayerAns.SourceCode);
            if (locationModels != null && locationModels.Count > 0)
            {
                var locationModel = locationModels.FirstOrDefault(a => a.DocType.ToLower() == dataContext.DataLayerAns.SourceCode.ToLower());
                if (!string.IsNullOrEmpty(locationModel.DocPath))
                {
                    DataModel model = XmlUtility.ConditionFirstOrDefaultDataModel(dataContext.DataLayerOpt.SourdatModleList, "", locationModel.DocPath);
                    if (model == null)
                    {
                        locationModel = locationConfigM.GetLocationModelByStage(causeStageXml, dataContext.DataLayerOpt.OptimizationXml, dataContext.DataLayerAns.CaseType);
                        locationModel.DocType = dataContext.DataLayerAns.SourceCode;
                        locationModels = new List<DOCLocationModel>();
                        locationModels.Add(locationModel);
                    }

                }
            }

            return locationModels;
        }
        /// <summary>
        /// 案由要素分人员优选
        /// </summary>
        public void Optimization()
        {
            Stopwatch stopwatch = new Stopwatch();
            SetModuleProcess(ModuleName, 0, dataContext.InteractiveShow.inputParameterModel);
            stopwatch.Start();
            try
            {
                //数据加载；
                var sourceMos = LoadData();
                XmlUtilCommon xmlUtilCommon = new XmlUtilCommon() { dataContext = dataContext };
                //记录原本的分析数据
                var sourceAnsisyModels = sourceMos.ansmos;
                //获取最新阶段的证据数据
                var stageModel = dataContext.DataLayerAns.StageProcessAnalysisModel;
                #region 屏蔽证据要素优选功能

                
                //if (stageModel != null)
                //{
                //    //最新阶段节点数据
                //    var stageData = XmlUtility.ConditionFirstOrDefaultDataModel(dataContext.DataLayerOpt.SourdatModleList, "", stageModel.path);
                //    //获取当前阶段下的所有子节点
                //    List<DataModel> allDataModels = xmlUtilCommon.SubordinateDataModelList(dataContext.DataLayerOpt.SourdatModleList, stageData);
                //    string oldsfid = dataContext.DataLayerAns.SF_ID;
                //    //获取证据节点下的详情节点
                //    var evidDetails = allDataModels.Where(x => x.XmlPath.EndsWith("详情") && x.XmlPath.Contains("证据") && !x.XmlPath.Contains("证据内容") && !x.XmlPath.Contains("证据要素")).ToList();
                //    if (evidDetails != null && evidDetails.Any())
                //    {
                //        if (dataContext.DataLayerOpt.EvidenceFactRelations == null)
                //            dataContext.DataLayerOpt.EvidenceFactRelations = new List<EvidenceFactRelationModel>();
                //        if (dataContext.DataLayerOpt.EvidenctNodeRecords == null)
                //            dataContext.DataLayerOpt.EvidenctNodeRecords = new List<EvidenctNodeRecord>();
                //        foreach (var item in evidDetails)
                //        {

                //            //获取证据详情下的所有子节点
                //            var evidContent = xmlUtilCommon.SubordinateDataModelList(allDataModels, item);
                //            //获取证据内容下详情节点集合
                //            var evidContentDetails = evidContent.Where(x => x.XmlPath.EndsWith("详情") && x.XmlPath.Contains("证据内容") && !x.XmlPath.Contains("证据要素"));
                //            if (evidContentDetails != null && evidContentDetails.Any())
                //            {
                //                foreach (var detailItem in evidContentDetails)
                //                {
                //                    if (dataContext.DataLayerOpt.ElementOptimizationResults != null && dataContext.DataLayerOpt.ElementOptimizationResults.Values.Any())
                //                    {
                //                        sourceMos.optmos = dataContext.DataLayerOpt.ElementOptimizationResults;
                //                    }
                //                    var sfid = detailItem.AttributesList.FirstOrDefault(x => x.Name == "证据文件ID")?.sourceList.FirstOrDefault()?.SaveValue;
                //                    dataContext.DataLayerAns.SF_ID = sfid;
                //                    var evidElementDatas = xmlUtilCommon.SubordinateDataModelList(evidContent, detailItem);
                //                    if (evidElementDatas.Any(x => x.XmlPath.Contains("案由要素")))
                //                    {
                //                        //获取证据要素节点xpath路径
                //                        var evidElementNode = evidElementDatas.FirstOrDefault(x => x.XmlPath.EndsWith("证据要素"));
                //                        var evidCauseDatas = evidElementDatas.Where(x => x.XmlPath.Contains("案由要素")).ToList();
                //                        List<DataModel> factDatas = new List<DataModel>();
                //                        foreach (var causeItem in evidCauseDatas)
                //                        {
                //                            causeItem.XmlPath.Replace(evidElementNode.XmlPath, "").Trim('/');
                //                            var factData = causeItem.Clone();
                //                            factData.XmlPath = factData.XmlPath.Replace(evidElementNode.XmlPath, "").Trim('/');
                //                            if (factData.sourceData != null && factData.sourceData.sourceList.Any())
                //                            {
                //                                factData.sourceData.sourceList.FirstOrDefault().SourceNodeId = causeItem.ID;
                //                                factData.sourceData.sourceList.FirstOrDefault().SourceID = sfid;
                //                            }
                //                            factDatas.Add(factData);

                //                        }
                //                        if (factDatas.Any())
                //                        {
                //                            var causeNode = factDatas.FirstOrDefault(x => x.XmlPath.EndsWith("案由要素"));
                //                            var ccid = dataContext.DataLayerAns.CaseCausesList[0].CC_ID;
                //                            //获取事实要素节点
                //                            var factNode = factDatas.FirstOrDefault(x => x.XmlPath.EndsWith("事实要素"));
                //                            //主张方节点
                //                            var advocata = item.Clone();
                //                            advocata.XmlPath = "案由要素/事实要素/主张方";
                //                            advocata.ID = Snowflake.Instance().GetId().ToString();
                //                            advocata.ParentId = factNode.ID;
                //                            var advocataNameAttr = advocata.AttributesList.FirstOrDefault(x => x.Name == "主张方姓名");
                //                            if (advocataNameAttr != null)
                //                                advocataNameAttr.Name = "主张方姓名或名称";
                //                            factDatas.Add(advocata);
                //                            xmlUtilCommon.DataModelIDByReset(factDatas, causeNode.ParentId, "");
                //                            var factCauseNode = factDatas.FirstOrDefault(x => x.XmlPath.EndsWith("案由要素"));
                //                            foreach (var factSubItem in factDatas.Where(x => x.ParentId == factCauseNode.ID))
                //                            {
                //                                factSubItem.ParentId = ccid;
                //                            }
                //                            factDatas.FirstOrDefault(x => x.XmlPath.EndsWith("案由要素")).ID = ccid;
                //                            sourceMos.ansmos = new Dictionary<string, List<DataModel>>();
                //                            sourceMos.ansmos.Add(ccid, factDatas);
                //                            Stopwatch evidStopwatch = new Stopwatch();
                //                            evidStopwatch.Start();
                //                            dataContext.InteractiveShow.LogShow($"sfid为【{sfid}】的证据执行分人员要素优选开始：{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")}");
                //                            CaseCauseElementOptimization(sourceMos.optmos, sourceMos.ansmos);
                //                            evidStopwatch.Stop();
                //                            dataContext.InteractiveShow.LogShow($"sfid为【{sfid}】的证据执行分人员要素优选结束：{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")},用时{evidStopwatch.Elapsed.TotalMilliseconds.ToString("0")}");
                //                        }
                //                        dataContext.DataLayerAns.SF_ID = oldsfid;
                //                    }
                //                }
                //            }
                //        }
                //    }
                //    dataContext.DataLayerAns.SF_ID = oldsfid;
                //    sourceMos.ansmos = sourceAnsisyModels;
                //}
                #endregion
                if (dataContext.DataLayerOpt.ElementOptimizationResults != null && dataContext.DataLayerOpt.ElementOptimizationResults.Values.Any())
                {
                    sourceMos.optmos = dataContext.DataLayerOpt.ElementOptimizationResults;
                }
                if (dataContext.DataLayerAns.causeChangeDataModelList.Count > 0 && dataContext.DataLayerAns.causeChangeDataModelList != null)
                {
                    foreach (ChangeDataModel changeDataModel in dataContext.DataLayerAns.causeChangeDataModelList)
                    {
                        if (changeDataModel.ChangeType.ToLower() == "a_node")
                        {
                            string xmlvalue = HttpHelp.DeCodeBase64new(65001, changeDataModel.ChangeValue);
                            HandleNodeAttr(xmlvalue);
                            XmlDocument xmlDocumentAdd = new XmlDocument();
                            xmlDocumentAdd.LoadXml(xmlvalue);
                            DataSoursModel dataSoursModel = xmlUtilCommon.GetXMLByDataModelBackFill(xmlDocumentAdd);
                            if (string.IsNullOrEmpty(changeDataModel.XmlPath))
                            {
                                List<DataModel> dataList = new List<DataModel>();
                                dataList = dataSoursModel.dataModelList;
                                DataModel dataModel = dataList.FirstOrDefault(a => a.ParentId == "");
                                string rootID = dataModel.ID;
                                if (dataModel.AttributesList.FirstOrDefault(a => a.Name.ToLower() == "案由id") != null)
                                {
                                    string causeid = dataModel.AttributesList.FirstOrDefault(a => a.Name.ToLower() == "案由id").sourceList.FirstOrDefault(a => a.IsCheck == "1").SaveValue;
                                    foreach (DataModel model in dataList.Where(a => a.ParentId == rootID))
                                    {
                                        model.ParentId = causeid;
                                    }
                                    dataModel.ID = causeid;
                                    sourceMos.ansmos = new Dictionary<string, List<DataModel>>();
                                    sourceMos.ansmos.Add(causeid, dataSoursModel.dataModelList);
                                }

                            }
                            else
                            {
                                if (sourceMos.optmos != null && sourceMos.optmos.Count > 0)
                                {
                                    var oplist = sourceMos.optmos.FirstOrDefault(a => a.Value.FirstOrDefault(b => b.ID == changeDataModel.NodeId) != null);
                                    if (oplist.Key != null)
                                    {
                                        DataModel dataModelRoot = oplist.Value.FirstOrDefault(a => a.ID == changeDataModel.NodeId);
                                        if (dataSoursModel != null && dataModelRoot != null)
                                        {
                                            foreach (DataModel model in dataSoursModel.dataModelList)
                                            {
                                                model.XmlPath = dataModelRoot.XmlPath + "/" + model.XmlPath;
                                            }
                                            XmlDocument ffdcc = XmlUtility.DataModelByXml(oplist.Value);
                                            List<DataModel> dataModelAsisList = xmlUtilCommon.SubParentDateModel(oplist.Value, dataModelRoot);
                                            dataSoursModel.dataModelList.FirstOrDefault(a => a.ParentId == "").ParentId = changeDataModel.NodeId;
                                            dataSoursModel.dataModelList.AddRange(dataModelAsisList);
                                            XmlDocument xmlDocumentff = XmlUtility.DataModelByXml(dataSoursModel.dataModelList);
                                            dataSoursModel = xmlUtilCommon.GetXMLByDataModelBackID(xmlDocumentff);
                                            sourceMos.ansmos = new Dictionary<string, List<DataModel>>();
                                            sourceMos.ansmos.Add(oplist.Key, dataSoursModel.dataModelList);
                                        }
                                    }
                                }

                            }
                            CaseCauseElementOptimization(sourceMos.optmos, sourceMos.ansmos);
                        }
                    }
                    sourceMos.ansmos = sourceAnsisyModels;
                }
                if (sourceMos.ansmos != null || sourceMos.ansmos.Count > 0)
                {
                    CaseCauseElementOptimization(sourceMos.optmos, sourceMos.ansmos);
                }
            }
            catch (Exception ex)
            {
                dataContext.InteractiveShow.LogShow("案由要素分人员优选错误:" + ex.Message, LogMessageType.Error);
            }
            stopwatch.Stop();
            SetModuleProcess(ModuleName + "_" + stopwatch.Elapsed.TotalMilliseconds.ToString("0"), 100, dataContext.InteractiveShow.inputParameterModel);
        }

        /// <summary>
        /// 去除xml所有节点下的id属性
        /// </summary>
        public string HandleNodeAttr(string xmlContent)
        {
            XDocument xDocument = XDocument.Parse(xmlContent);
            var xElementList = xDocument.Elements();
            if (xElementList != null && xElementList.Any())
            {
                foreach (var item in xElementList)
                {
                    DeleteNodeIdAttr(item);
                }
            }
            var content = xDocument.ToString();
            return content;
        }

        /// <summary>
        /// 删除节点id属性
        /// </summary>
        /// <param name="xElement"></param>
        private void DeleteNodeIdAttr(XElement xElement)
        {
            var idAttr = xElement.Attribute("id");
            if (idAttr != null)
            {
                idAttr.Remove();
            }
            var childs = xElement.Elements();
            if (childs != null && childs.Any())
            {
                foreach (XElement child in childs)
                {
                    DeleteNodeIdAttr(child);
                }
            }
        }

        /// <summary>
        /// 案由要素优选
        /// </summary>
        /// <param name="dicDataModelOpList">上次优选结果数据</param>
        /// <param name="dicDataModelAsList">本地分析结果</param>
        private void CaseCauseElementOptimization(Dictionary<string, List<DataModel>> dicDataModelOpList, Dictionary<string, List<DataModel>> dicDataModelAsList)
        {
            var oplist = dicDataModelOpList.FirstOrDefault().Value;
            Dictionary<string, List<DataModel>> DicvaluePairList = new Dictionary<string, List<DataModel>>();
            if (dicDataModelAsList != null && dicDataModelAsList.Count > 0)
            {
                foreach (var dataModelAs in dicDataModelAsList)
                {
                    //案由ID
                    string causeID = dataModelAs.Key;
                    if (dicDataModelOpList != null && dicDataModelOpList.Count > 0)
                    {
                        if (dicDataModelOpList.ContainsKey(causeID))
                        {
                            //存在该案由的案由要素优选结果
                            List<DataModel> dataModelOpList = dicDataModelOpList[causeID];
                            RomveData(dataModelOpList);
                            if (dataModelOpList.Count == 0)
                            {
                                //不存在该案由优选结果分析结果即为优选结果
                                DicvaluePairList.Add(dataModelAs.Key, dataModelAs.Value);
                            }
                            else
                            {
                                for (int i = 0; i < dataModelAs.Value.Count; i++)
                                {
                                    dataModelAs.Value[i].sourceData.sourceList[0].AnalysisStatus = "1";
                                }
                                List<DataModel> ReturndataModelList = new List<DataModel>();
                                List<DataModel> dataModelsAissNodeList = dataModelAs.Value.Where(a => a.XmlPath.IndexOf("主张方") > -1).ToList();
                                List<DataModel> dataModelsOPPersonnelList = dataModelOpList.Where(a => a.XmlPath.IndexOf("主张方") > -1).ToList();
                                dataModelsOPPersonnelList = dataModelsOPPersonnelList.Select(item => item.Clone()).ToList();

                                foreach (DataModel itemAdvocate in dataModelsAissNodeList)
                                {
                                    DataModel dataModelasisPrentNode = dataModelAs.Value.FirstOrDefault(a => a.ID == itemAdvocate.ParentId);
                                    if (dataModelasisPrentNode.ParentId == dataContext.DataCommon.CaseCausesList[0].CC_ID)
                                    {
                                        AttributeInfo itemNameDataModel = itemAdvocate.AttributesList.FirstOrDefault(a => a.Name == "主张方姓名或名称");
                                        if (itemNameDataModel != null)
                                        {
                                            string name = itemNameDataModel.sourceList.FirstOrDefault(a => a.IsCheck == "1").SaveValue;
                                            string suitid = itemAdvocate.AttributesList.FirstOrDefault(a => a.Name == "主张方诉讼地位").sourceList.FirstOrDefault(a => a.IsCheck == "1").SaveValue;
                                            //获取结果要素对应节点信息
                                            DataModel petitionDatamodel = new DataModel();
                                            try
                                            {
                                                petitionDatamodel = dataModelOpList.FirstOrDefault(a => a.XmlPath == dataModelasisPrentNode.XmlPath + "/主张方" && a.AttributesList.FirstOrDefault(b => b.Name == "主张方姓名或名称").sourceList.FirstOrDefault(c => c.IsCheck == "1").SaveValue == name
                                                 && a.AttributesList.FirstOrDefault(g => g.Name == "主张方诉讼地位").sourceList.FirstOrDefault(c => c.IsCheck == "1").SaveValue == suitid);
                                                if (petitionDatamodel != null)
                                                {
                                                    DataModel dataModelPRomve = dataModelsOPPersonnelList.FirstOrDefault(a => a.ID == petitionDatamodel.ID);
                                                    dataModelsOPPersonnelList.Remove(dataModelPRomve);
                                                    petitionDatamodel = dataModelOpList.FirstOrDefault(a => a.ID == petitionDatamodel.ParentId);
                                                }
                                            }
                                            catch (Exception)
                                            {
                                                dataContext.InteractiveShow.LogShow("根据主张方查询案由要素错误，人员姓名" + name + "诉讼地位：" + suitid);
                                            }
                                            List<DataModel> dataModelCuases = new List<DataModel>();
                                            string elementid = "";
                                            if (itemAdvocate.XmlPath.IndexOf("诉请要素") > -1)
                                            {
                                                elementid = "1";
                                                if (petitionDatamodel != null)
                                                {
                                                    dataModelCuases = SubordinateDataModelList(dataModelOpList, petitionDatamodel);
                                                }
                                                else
                                                {
                                                    dataModelCuases = SubordinateDataModelList(dataModelAs.Value, dataModelasisPrentNode);
                                                }

                                            }
                                            else if (itemAdvocate.XmlPath.IndexOf("事实要素") > -1)
                                            {
                                                elementid = "2";
                                                if (petitionDatamodel != null && petitionDatamodel.ID != null)
                                                {
                                                    dataModelCuases = SubordinateDataModelList(dataModelOpList, petitionDatamodel);
                                                }
                                                else
                                                {
                                                    dataModelCuases = SubordinateDataModelList(dataModelAs.Value, dataModelasisPrentNode);
                                                }
                                            }
                                            else if (itemAdvocate.XmlPath.IndexOf("结果要素") > -1)
                                            {
                                                elementid = "5";
                                                if (petitionDatamodel != null && petitionDatamodel.ID != null)
                                                {
                                                    dataModelCuases = SubordinateDataModelList(dataModelOpList, petitionDatamodel);
                                                }
                                                else
                                                {
                                                    dataModelCuases = SubordinateDataModelList(dataModelAs.Value, dataModelasisPrentNode);
                                                }
                                            }
                                            if (base.OptimizeElement.CaseTypeList.FirstOrDefault(a => a.Code == suitid) != null)
                                            {
                                                if (suitid == "t2")
                                                {
                                                    elementid = "4";
                                                }
                                                List<Xmllable> xmllableList = base.OptimizeElement.CaseTypeList.FirstOrDefault(x => x.Code == suitid && x.XmlFactTypeList.FirstOrDefault(b => b.Type == elementid) != null)?
                                                                            .XmlFactTypeList.FirstOrDefault(f => f.Type == elementid)?.XmllableList;
                                                string xmltype = "";
                                                string xmlpriority = "";
                                                foreach (Xmllable xmllable in xmllableList)
                                                {
                                                    if (string.IsNullOrEmpty(xmllable.Type))
                                                    {
                                                        xmllable.Type = xmltype;
                                                    }
                                                    else
                                                    {
                                                        xmltype = xmllable.Type;
                                                    }
                                                    if (string.IsNullOrEmpty(xmllable.Priority))
                                                    {
                                                        xmllable.Priority = xmlpriority;
                                                    }
                                                    else
                                                    {
                                                        xmlpriority = xmllable.Priority;
                                                    }
                                                }
                                                //分析结果数据
                                                List<DataModel> dataModelsAsisList = SubordinateDataModelList(dataModelAs.Value, dataModelasisPrentNode);
                                                dataModelsAsisList = dataModelsAsisList.Select(item => item.Clone()).ToList();
                                                //案由要素优选
                                                if (dataModelCuases.Count == 0)
                                                {
                                                    dataModelCuases = dataModelsAsisList;
                                                }
                                                else
                                                {
                                                    CaseElmentOptimization(dataModelsAsisList, dataModelAs.Key, dataModelCuases, xmllableList);
                                                }
                                                if (dataModelCuases != null && dataModelCuases.Count > 0)
                                                {
                                                    dataModelCuases = dataModelCuases.Where(a => a.State != "2").ToList();
                                                    dataModelCuases = dataModelCuases.Where(a => a.sourceData.sourceList.FirstOrDefault(b => b.AnalysisStatus != "0") != null).ToList();
                                                }
                                                if (ReturndataModelList.Count == 0)
                                                {
                                                    ReturndataModelList.AddRange(dataModelCuases);
                                                }
                                                else
                                                {
                                                    foreach (DataModel dataModel in dataModelCuases.Where(a => a.XmlPath.Split('/')[a.XmlPath.Split('/').Length - 1] == "诉请要素" || a.XmlPath.Split('/')[a.XmlPath.Split('/').Length - 1] == "事实要素"))
                                                    {
                                                        //dataModel.ParentId = dataModelAs.Key;
                                                        if (ReturndataModelList.FirstOrDefault(a => a.ID == dataModel.ID) == null)
                                                        {
                                                            ReturndataModelList.AddRange(SubordinateDataModelList(dataModelCuases, dataModel));

                                                        }
                                                    }
                                                }


                                            }
                                        }
                                    }
                                }

                                foreach (DataModel personnelModel in dataModelsOPPersonnelList)
                                {
                                    DataModel dataModelRoot = dataModelOpList.FirstOrDefault(a => a.ID == personnelModel.ParentId);
                                    List<DataModel> dataModelValueList = SubordinateDataModelList(dataModelOpList, dataModelRoot);
                                    ReturndataModelList.AddRange(dataModelValueList);
                                }
                                ReturndataModelList = ReturndataModelList.Distinct().ToList();
                                List<DataModel>  mlist= ReturndataModelList.Where(a => a.sourceData.sourceList.FirstOrDefault(b => b.AnalysisStatus != "0") != null).ToList();
                                DicvaluePairList.Add(causeID, ReturndataModelList);
                            }


                        }
                        else
                        {
                            //不存在该案由优选结果分析结果即为优选结果
                            DicvaluePairList.Add(dataModelAs.Key, dataModelAs.Value);
                        }
                    }
                    else
                    {
                        DicvaluePairList.Add(dataModelAs.Key, dataModelAs.Value);
                        //不存在优选结果，分析结果即是优选结果

                    }

                }
            }
            else
            {
                if (dicDataModelOpList != null && dicDataModelOpList.Count > 0)
                {
                    DicvaluePairList = dicDataModelOpList;
                }
            }

            if (DicvaluePairList != null && DicvaluePairList.Count > 0)
            {
                CaseElementListByCauseElmentList(dataContext.DataLayerOpt.SourdatModleList, DicvaluePairList);
            }
        }

        /// <summary>
        /// 案件信息优选
        /// </summary>
        /// <param name="dataModelAsisList"></param>
        /// <param name="prentID"></param>
        /// <param name="dataModelsOPList"></param>
        private void CasecaseuseElmentOptimization(List<DataModel> dataModelAsisList, string prentID, List<DataModel> dataModelsOPList, List<Xmllable> XmllableList)
        {
            List<DataModel> dataModelsAissNodeList = new List<DataModel>();

            dataModelsAissNodeList = dataModelAsisList.Where(a => a.ParentId == prentID).ToList();
            if (dataModelsAissNodeList.Count > 0)
            {
                Xmllable xmllableCofigs = XmllableList.FirstOrDefault(a => a.Xmlpath == dataModelsAissNodeList[0].XmlPath);
                if (xmllableCofigs != null && xmllableCofigs.Type == "b")
                {
                    dataContext.InteractiveShow.LogShow("进入优先模式B" + xmllableCofigs.Xmlpath);
                    //单一数据源优选
                    #region 单一数据源
                    string parentid = "";
                    DataModel dataOpModel = new DataModel();
                    if (dataModelsOPList.FirstOrDefault(a => a.XmlPath == xmllableCofigs.Xmlpath && a.State != "2") == null)
                    {
                        string xmlpath = "";
                        for (int i = 0; i < xmllableCofigs.Xmlpath.Split('/').Length - 1; i++)
                        {
                            if (xmlpath == "")
                            {
                                xmlpath = xmllableCofigs.Xmlpath.Split('/')[i];
                            }
                            else
                            {
                                xmlpath = xmlpath + "/" + xmllableCofigs.Xmlpath.Split('/')[i];
                            }
                        }
                        if (dataModelsOPList.FirstOrDefault(a => a.XmlPath == xmlpath && a.State != "2") != null)
                        {
                            parentid = dataModelsOPList.FirstOrDefault(a => a.XmlPath == xmlpath).ID;
                            dataModelsAissNodeList[0].ParentId = parentid;
                            List<DataModel> dataModelListRestAiss = SubordinateDataModelList(dataModelAsisList, dataModelsAissNodeList[0]);
                            foreach (DataModel aissmodel in dataModelListRestAiss)
                            {
                                aissmodel.State = "1";
                                dataModelsOPList.Add(aissmodel);
                            }
                        }
                    }
                    else
                    {
                        dataOpModel = dataModelsOPList.FirstOrDefault(a => a.XmlPath == xmllableCofigs.Xmlpath && a.State != "2");
                        string modesours = dataOpModel.sourceData.sourceList.FirstOrDefault(a => a.IsCheck == "1").SourceCode;
                        string soursnameopid = OptimizeElement.Sourcedatadefine[0].SourcedataList.FirstOrDefault(a => a.Code.ToLower() == modesours.ToLower()).id.ToString();
                        string soursnameasisid = OptimizeElement.Sourcedatadefine[0].SourcedataList.FirstOrDefault(a => a.Code.ToLower() == dataContext.DataLayerAns.SourceCode.ToLower()).id.ToString();
                        int opsum = ListByCount(xmllableCofigs.Priority.Split('>').ToList(), soursnameopid);
                        int assum = ListByCount(xmllableCofigs.Priority.Split('>').ToList(), soursnameasisid);
                        if (assum <= opsum)
                        {

                            if (dataModelsOPList.FirstOrDefault(a => a.XmlPath == xmllableCofigs.Xmlpath && a.State != "2") != null)
                            {
                                List<DataModel> dataModelListOp = dataModelsOPList.Where(a => a.XmlPath == xmllableCofigs.Xmlpath && a.State != "2").ToList();
                                foreach (DataModel dataop in dataModelListOp)
                                {
                                    List<DataModel> dataModelListRest = SubordinateDataModelList(dataModelsOPList, dataop);
                                    parentid = dataop.ParentId;
                                    foreach (DataModel dataModelOP in dataModelListRest)
                                    {
                                        dataModelOP.State = "2";
                                    }
                                }
                            }

                            foreach (DataModel dataModelAiss in dataModelsAissNodeList)
                            {
                                if (dataModelsOPList.FirstOrDefault(a => a.XmlPath == dataModelAiss.XmlPath && a.State != "2") == null)
                                {
                                    List<DataModel> dataModelListRestAiss = SubordinateDataModelList(dataModelAsisList, dataModelAiss);
                                    dataModelListRestAiss.FirstOrDefault(a => a.ID == dataModelAiss.ID).ParentId = parentid;
                                    //dataModelListRestAiss = JsonConvert.DeserializeObject<List<DataModel>>(JsonConvert.SerializeObject(dataModelListRestAiss));
                                    dataModelListRestAiss = dataModelListRestAiss.Select(item => item.Clone()).ToList();
                                    foreach (DataModel aissmodel in dataModelListRestAiss)
                                    {
                                        aissmodel.State = "1";
                                        dataModelsOPList.Add(aissmodel);
                                    }
                                }
                            }
                        }

                    }

                    #endregion
                }
                else
                {
                    #region 多数据源优选
                    foreach (DataModel dataModelAsisNode in dataModelsAissNodeList)
                    {
                        List<DataModel> dataModelListAsis = new List<DataModel>();//分析下级循环合集
                        List<DataModel> dataModelListOP = new List<DataModel>();//优选下级循环合集
                        dataModelListAsis = dataModelAsisList;
                        dataModelListOP = dataModelsOPList;
                        Xmllable xmllableCofig = XmllableList.FirstOrDefault(a => a.Xmlpath == dataModelAsisNode.XmlPath);
                        if (xmllableCofig != null)
                        {
                            bool determine = true;
                            if (xmllableCofig.ConditionList.Count > 0)
                            {
                                try
                                {
                                    determine = base.ConditionDetermine(xmllableCofig.ConditionList);
                                }
                                catch (Exception ef)
                                {
                                }
                            }
                            if (determine)
                            {
                                DataModel dataModelOpSging = new DataModel();
                                if (xmllableCofig.Type == "a")
                                {
                                    foreach (var element in xmllableCofig.SignnodeList.NodeList)
                                    {
                                        if (dataModelAsisNode.AttributesList.FirstOrDefault(a => a.Name == element.Code) != null)
                                        {
                                            string elementvalue = dataModelAsisNode.AttributesList.FirstOrDefault(a => a.Name == element.Code).sourceList.FirstOrDefault(a => a.IsCheck == "1").SaveValue;
                                            dataContext.InteractiveShow.LogShow("进入标识优选值：" + elementvalue);
                                            if (elementvalue != null)
                                            {
                                                dataContext.InteractiveShow.LogShow("标识列不为空：" + elementvalue);
                                                dataModelOpSging = dataModelListOP.FirstOrDefault(a => a.XmlPath == xmllableCofig.Xmlpath && a.AttributesList.FirstOrDefault(b => b.Name == element.Code &&
                                                 b.sourceList.FirstOrDefault(s => s.IsCheck == "1" && s.SaveValue == elementvalue) != null) != null);
                                                if (dataModelOpSging != null)
                                                {

                                                    dataModelListOP = SubordinateDataModelList(dataModelsOPList, dataModelOpSging);
                                                    List<DataModel> parentNodeModel = ParendNodeDataModelList(dataModelsOPList, dataModelOpSging);
                                                    dataModelListOP.AddRange(parentNodeModel);

                                                }
                                            }
                                            else
                                            {
                                                dataContext.InteractiveShow.LogShow("标识列为空：" + elementvalue);

                                            }
                                            break;
                                        }
                                    }
                                }
                                else
                                {
                                    dataModelOpSging = dataModelListOP.FirstOrDefault(a => a.XmlPath == xmllableCofig.Xmlpath && a.State != "2");
                                }


                                base.OptimizationData(dataModelAsisNode, dataModelOpSging, xmllableCofig, dataModelListOP, dataModelAsisList, OptimizeElement.Sourcedatadefine);
                            }
                            CasecaseuseElmentOptimization(dataModelAsisList, dataModelAsisNode.ID, dataModelListOP, XmllableList);
                            foreach (DataModel opModel in dataModelListOP)
                            {
                                if (dataModelsOPList.FirstOrDefault(a => a.ID == opModel.ID && a.State == opModel.State) != null)
                                {

                                    DataModel model = dataModelsOPList.FirstOrDefault(a => a.ID == opModel.ID);
                                    model = opModel;

                                }
                                else
                                {
                                    dataModelsOPList.Add(opModel);
                                }
                            }
                        }
                        else
                        {
                            DataModel dataModelOpSging = dataModelListOP.FirstOrDefault(a => a.XmlPath == dataModelAsisNode.XmlPath && a.State != "2");
                            if (dataModelOpSging == null)
                            {
                                //获取上级节点信息
                                string parentxml = "";
                                List<string> pathlist = dataModelAsisNode.XmlPath.Split('/').ToList();
                                pathlist.RemoveAt(pathlist.Count - 1);
                                parentxml = string.Join("/", pathlist);
                                CaseNodeUpdate(dataModelListOP, parentxml);
                                DataModel nodeParent = dataModelListOP.FirstOrDefault(a => a.XmlPath == parentxml && a.State != "2");
                                if (nodeParent != null)
                                {
                                    DataModel dataModelAddNode = dataModelAsisNode.Clone();
                                    dataModelAddNode.ParentId = nodeParent.ID;
                                    dataModelListOP.Add(dataModelAddNode);
                                    dataModelsOPList.Add(dataModelAddNode);
                                }

                            }
                            else
                            {
                                List<DataModel> opList = dataModelListOP.Where(a => a.XmlPath == dataModelAsisNode.XmlPath && a.State != "2").ToList();
                                if (opList.Count > 0)
                                {
                                    if (!ISsameNode(opList, dataModelAsisNode))
                                    {
                                        //不存在该节点
                                        string parentxml = "";
                                        List<string> pathlist = dataModelAsisNode.XmlPath.Split('/').ToList();
                                        pathlist.RemoveAt(pathlist.Count - 1);
                                        parentxml = string.Join("/", pathlist);
                                        if (string.IsNullOrEmpty(parentxml))
                                        {
                                            parentxml = dataModelAsisNode.XmlPath;
                                        }
                                        else
                                        {
                                            CaseNodeUpdate(dataModelListOP, parentxml);
                                        }
                                        DataModel nodeParent = dataModelListOP.FirstOrDefault(a => a.XmlPath == parentxml && a.State != "2");
                                        DataModel dataModelAddNode = dataModelAsisNode.Clone();
                                        dataModelAddNode.ParentId = nodeParent.ID;
                                        dataModelListOP.Add(dataModelAddNode);
                                    }
                                }
                            }
                            CasecaseuseElmentOptimization(dataModelAsisList, dataModelAsisNode.ID, dataModelsOPList, XmllableList);
                        }

                    }
                    #endregion
                }
            }
        }

        /// <summary>
        /// 案件信息优选
        /// </summary>
        /// <param name="dataModelAsisList">分析数据结果</param>
        /// <param name="prentID">分析数据父级Id</param>
        /// <param name="dataModelsOPList">上次优先结果数据</param>
        public void CaseElmentOptimization(List<DataModel> dataModelAsisList, string prentID, List<DataModel> dataModelsOPList, List<Xmllable> XmllableList)
        {
            List<DataModel> dataModelsAissNodeList = new List<DataModel>();
            if (dataContext.DataLayerAns.ExtractCaseCausesList != null && dataContext.DataLayerAns.ExtractCaseCausesList.Count > 0)
            {
                //dataModelsAissNodeList = dataModelAsisList.Where(a => a.ParentId == prentID && a.XmlPath.IndexOf(dataContext.DataLayerAns.CaseCausesList[0].CC_Name) <=0).ToList();
                dataModelsAissNodeList = dataModelAsisList.Where(a => a.ParentId == prentID && a.XmlPath.IndexOf("案由要素") <= 0).ToList();
            }
            else
            {
                dataModelsAissNodeList = dataModelAsisList.Where(a => a.ParentId == prentID).ToList();
            }
            if (dataModelsAissNodeList.Count > 0)
            {

                foreach (DataModel dataModelAsisNode in dataModelsAissNodeList)
                {
                    Xmllable xmllableCofigs = XmllableList.FirstOrDefault(a => a.Xmlpath == dataModelAsisNode.XmlPath);
                    #region 多值优选合并
                    string containSource = xmllableCofigs?.ContainSources;
                    if(!string.IsNullOrWhiteSpace(containSource))
                    {
                        containSource = containSource.ToLower();
                        List<string> containList = containSource.Split(',', StringSplitOptions.RemoveEmptyEntries).ToList();
                        if(containList!=null && containList.Contains(dataContext.DataLayerAns.SourceCode.ToLower()))
                        {
                            var containElement = xmllableCofigs.ElementList.FirstOrDefault(x => x.IsContain == "1");
                            if(containElement!=null)
                            {
                                string elementName = containElement.Name;
                                //分析数据的属性值
                                var asisAttrValue = dataModelAsisNode.AttributesList.FirstOrDefault(a => a.Name == elementName)?.sourceList.FirstOrDefault(a => a.IsCheck == "1")?.SaveValue;
                                if (!string.IsNullOrWhiteSpace(asisAttrValue))
                                {
                                    List<string> asisValueList = asisAttrValue.Split(',', StringSplitOptions.RemoveEmptyEntries).ToList();
                                    var optNodes = dataModelsOPList.Where(a => a.XmlPath == xmllableCofigs.Xmlpath && a.State != "2" && a.sourceData.sourceList.Any(x => x.IsCheck == "1")).Select(x=>x.Clone()).ToList();
                                    if(optNodes!=null && optNodes.Any())
                                    {
                                        bool isContainMerge = false;
                                        var optContainNodes= optNodes.Where(a => !string.IsNullOrWhiteSpace(a.AttributesList.FirstOrDefault(a => a.Name == elementName)?.sourceList.FirstOrDefault(a => a.IsCheck == "1")?.SaveValue));
                                        if(optContainNodes!=null && optContainNodes.Any())
                                        {
                                            foreach (var nodeItem in optContainNodes)
                                            {
                                                string optAttrValue = nodeItem.AttributesList.FirstOrDefault(a => a.Name == elementName)?.sourceList.FirstOrDefault(a => a.IsCheck == "1")?.SaveValue;
                                                List<string> optValueList = optAttrValue.Split(',', StringSplitOptions.RemoveEmptyEntries).ToList();
                                                //取交集数据
                                                var sameList = asisValueList.Intersect(optValueList).ToList();
                                                if (sameList != null && sameList.Any())
                                                {
                                                    //如果有交集数据就合并数据
                                                    var mergeList = asisValueList.Union(optValueList);
                                                    dataModelsOPList.FirstOrDefault(x=>x.ID==nodeItem.ID).AttributesList.FirstOrDefault(a => a.Name == elementName).sourceList.FirstOrDefault(a => a.IsCheck == "1").SaveValue = string.Join(',', mergeList);
                                                    var optSubList = SubordinateDataModelList(dataModelsOPList, nodeItem);
                                                    CaseElmentOptimization(dataModelAsisList, dataModelAsisNode.ID, optSubList, XmllableList);
                                                    //将数据更新到优选结果中
                                                    foreach (DataModel opModel in optSubList)
                                                    {
                                                        if (dataModelsOPList.FirstOrDefault(a => a.ID == opModel.ID && a.State == opModel.State) != null)
                                                        {
                                                            DataModel model = dataModelsOPList.FirstOrDefault(a => a.ID == opModel.ID);
                                                            model = opModel;
                                                        }
                                                        else
                                                        {
                                                            dataModelsOPList.Add(opModel);
                                                        }
                                                    }
                                                    isContainMerge = true;
                                                }
                                            }
                                        }
                                        //如果分析节点数据的属性值和优选数据的属性值不存在相同的，则强制与路径相同的第一个优选结果数据合并
                                        if(!isContainMerge)
                                        {
                                            var mergeNode = optNodes.FirstOrDefault();
                                            var asisAttrSour = dataModelAsisNode.AttributesList.FirstOrDefault(a => a.Name == elementName)?.sourceList.FirstOrDefault(a => a.IsCheck == "1");
                                            if (mergeNode.AttributesList.Any(x=>x.Name==elementName))
                                            {
                                                string optAttrValue = mergeNode.AttributesList.FirstOrDefault(a => a.Name == elementName)?.sourceList.FirstOrDefault(a => a.IsCheck == "1")?.SaveValue;
                                                List<string> optValueList = new List<string>();
                                                if (!string.IsNullOrWhiteSpace(optAttrValue))
                                                {
                                                    var splitList = optAttrValue.Split(',', StringSplitOptions.RemoveEmptyEntries).ToList();
                                                    if (splitList != null && splitList.Any())
                                                        optValueList.AddRange(splitList);
                                                }
                                                var mergeList = asisValueList.Union(optValueList);
                                                var mergeSource = mergeNode.AttributesList.FirstOrDefault(a => a.Name == elementName)?.sourceList.FirstOrDefault(a => a.IsCheck == "1");
                                                if (mergeSource != null)
                                                {
                                                    dataModelsOPList.FirstOrDefault(x => x.ID == mergeNode.ID).AttributesList.FirstOrDefault(a => a.Name == elementName).sourceList.FirstOrDefault(a => a.IsCheck == "1").SaveValue = string.Join(',', mergeList);
                                                }
                                            }
                                            else
                                            {
                                                var asisAttr = dataModelAsisNode.AttributesList.FirstOrDefault(a => a.Name == elementName && a.sourceList.Any(s => s.IsCheck == "1"));
                                                AttributeInfo attributeTmp = new AttributeInfo();
                                                attributeTmp.Name = elementName;
                                                attributeTmp.DictionariesCode = asisAttr.DictionariesCode;
                                                attributeTmp.Priority = asisAttr.Priority;
                                                attributeTmp.sourceList = new List<Source>();
                                                attributeTmp.sourceList.Add(asisAttrSour);
                                                mergeNode.AttributesList.Add(attributeTmp);
                                            }
                                            var optSubList = SubordinateDataModelList(dataModelsOPList, mergeNode);
                                            CaseElmentOptimization(dataModelAsisList, dataModelAsisNode.ID, optSubList, XmllableList);
                                            //将数据更新到优选结果中
                                            foreach (DataModel opModel in optSubList)
                                            {
                                                if (dataModelsOPList.FirstOrDefault(a => a.ID == opModel.ID && a.State == opModel.State) != null)
                                                {
                                                    DataModel model = dataModelsOPList.FirstOrDefault(a => a.ID == opModel.ID);
                                                    model = opModel;
                                                }
                                                else
                                                {
                                                    dataModelsOPList.Add(opModel);
                                                }
                                            }
                                        }
                                        continue;  
                                    }
                                }
                            }
                        }
                    }
                    #endregion
                    if (xmllableCofigs != null && xmllableCofigs.Type == "b")
                    {
                        dataContext.InteractiveShow.LogShow("进入优先模式B" + xmllableCofigs.Xmlpath);
                        //单一数据源优选
                        #region 单一数据源
                        string parentid = "";
                        DataModel dataOpModel = new DataModel();
                        if (dataModelsOPList.FirstOrDefault(a => a.XmlPath == xmllableCofigs.Xmlpath && a.State != "2") == null)
                        {
                            string xmlpath = "";
                            for (int i = 0; i < xmllableCofigs.Xmlpath.Split('/').Length - 1; i++)
                            {
                                if (xmlpath == "")
                                {
                                    xmlpath = xmllableCofigs.Xmlpath.Split('/')[i];
                                }
                                else
                                {
                                    xmlpath = xmlpath + "/" + xmllableCofigs.Xmlpath.Split('/')[i];
                                }
                            }
                            if (dataModelsOPList.FirstOrDefault(a => a.XmlPath == xmlpath && a.State != "2") != null)
                            {
                                parentid = dataModelsOPList.FirstOrDefault(a => a.XmlPath == xmlpath).ID;
                                dataModelAsisNode.ParentId = parentid;
                                List<DataModel> dataModelListRestAiss = SubordinateDataModelList(dataModelAsisList, dataModelAsisNode);
                                foreach (DataModel aissmodel in dataModelListRestAiss)
                                {
                                    aissmodel.State = "1";
                                    dataModelsOPList.Add(aissmodel);
                                }
                            }
                        }
                        else
                        {
                            dataOpModel = dataModelsOPList.FirstOrDefault(a => a.XmlPath == xmllableCofigs.Xmlpath && a.State != "2");
                            string modesours = dataOpModel.sourceData.sourceList.FirstOrDefault(a => a.IsCheck == "1").SourceCode;
                            string soursnameopid = OptimizeElement.Sourcedatadefine[0].SourcedataList.FirstOrDefault(a => a.Code.ToLower() == modesours.ToLower()).id.ToString();
                            string soursnameasisid = OptimizeElement.Sourcedatadefine[0].SourcedataList.FirstOrDefault(a => a.Code.ToLower() == dataContext.DataLayerAns.SourceCode.ToLower()).id.ToString();
                            int opsum = ListByCount(xmllableCofigs.Priority.Split('>').ToList(), soursnameopid);
                            int assum = ListByCount(xmllableCofigs.Priority.Split('>').ToList(), soursnameasisid);
                            if (assum < opsum)
                            {

                                if (dataModelsOPList.FirstOrDefault(a => a.XmlPath == xmllableCofigs.Xmlpath && a.State != "2") != null)
                                {
                                    List<DataModel> dataModelListOp = dataModelsOPList.Where(a => a.XmlPath == xmllableCofigs.Xmlpath && a.State != "2").ToList();
                                    foreach (DataModel dataop in dataModelListOp)
                                    {
                                        List<DataModel> dataModelListRest = SubordinateDataModelList(dataModelsOPList, dataop);
                                        parentid = dataop.ParentId;
                                        foreach (DataModel dataModelOP in dataModelListRest)
                                        {
                                            dataModelOP.State = "2";
                                        }
                                    }
                                }

                                foreach (DataModel dataModelAiss in dataModelsAissNodeList)
                                {
                                    if (dataModelsOPList.FirstOrDefault(a => a.XmlPath == dataModelAiss.XmlPath && a.State != "2") == null)
                                    {
                                        List<DataModel> dataModelListRestAiss = SubordinateDataModelList(dataModelAsisList, dataModelAiss);
                                        dataModelListRestAiss.FirstOrDefault(a => a.ID == dataModelAiss.ID).ParentId = parentid;
                                        dataModelListRestAiss = JsonConvert.DeserializeObject<List<DataModel>>(JsonConvert.SerializeObject(dataModelListRestAiss));
                                        foreach (DataModel aissmodel in dataModelListRestAiss)
                                        {
                                            aissmodel.State = "1";
                                            dataModelsOPList.Add(aissmodel);
                                        }
                                    }
                                }
                            }
                            if (assum == opsum)
                            {
                                if (dataModelsOPList.FirstOrDefault(a => a.XmlPath == xmllableCofigs.Xmlpath && a.State != "2") != null)
                                {
                                    List<DataModel> dataModelListOp = dataModelsOPList.Where(a => a.XmlPath == xmllableCofigs.Xmlpath && a.State != "2").ToList();
                                    foreach (DataModel dataop in dataModelListOp)
                                    {
                                        List<DataModel> dataModelListRest = SubordinateDataModelList(dataModelsOPList, dataop);
                                        parentid = dataop.ParentId;
                                        foreach (DataModel dataModelOP in dataModelListRest)
                                        {
                                            dataModelOP.State = "2";
                                        }
                                    }
                                }

                                foreach (DataModel dataModelAiss in dataModelsAissNodeList)
                                {
                                    if (dataModelsOPList.FirstOrDefault(a => a.XmlPath == dataModelAiss.XmlPath && a.State != "2") == null)
                                    {
                                        List<DataModel> dataModelListRestAiss = SubordinateDataModelList(dataModelAsisList, dataModelAiss);
                                        dataModelListRestAiss.FirstOrDefault(a => a.ID == dataModelAiss.ID).ParentId = parentid;
                                        dataModelListRestAiss = JsonConvert.DeserializeObject<List<DataModel>>(JsonConvert.SerializeObject(dataModelListRestAiss));
                                        foreach (DataModel aissmodel in dataModelListRestAiss)
                                        {
                                            aissmodel.State = "1";
                                            dataModelsOPList.Add(aissmodel);
                                        }
                                    }
                                }
                            }
                        }

                        #endregion
                    }
                    else
                    {
                        #region 多数据源优选
                        dataContext.InteractiveShow.LogShow("当前分析的路径" + dataModelAsisNode.XmlPath);
                        dataContext.InteractiveShow.LogShow("当前分析的id" + dataModelAsisNode.ID);
                        List<DataModel> dataModelListAsis = new List<DataModel>();//分析下级循环合集
                        List<DataModel> dataModelListOP = new List<DataModel>();//优选下级循环合集
                        dataModelListAsis = dataModelAsisList;
                        dataModelListOP = dataModelsOPList;
                        Xmllable xmllableCofig = XmllableList.FirstOrDefault(a => a.Xmlpath == dataModelAsisNode.XmlPath);
                        if (xmllableCofig != null)
                        {
                            #region TODO:ZSW 证据与事实要素关系
                            bool isIdentifierOpt = false;
                            bool isSingleSourceOpt = false;
                            string oldConfigType = xmllableCofig.Type;
                            if (!string.IsNullOrWhiteSpace(xmllableCofig.Type))
                            {
                                List<string> configTypes = xmllableCofig.Type.Split(">").ToList();
                                if (configTypes.Contains("a"))
                                    isIdentifierOpt = true;
                                if (configTypes.Contains("b"))
                                    isSingleSourceOpt = true;
                            }
                            #endregion
                            bool determine = true;
                            if (xmllableCofig.ConditionList.Count > 0)
                            {
                                try
                                {
                                    determine = ConditionDetermine(xmllableCofig.ConditionList);
                                }
                                catch (Exception ef)
                                {
                                    dataContext.InteractiveShow.LogShow("当前数据项条件解析错误，配置信息：" + JsonConvert.SerializeObject(ef.ToString()));
                                    dataContext.InteractiveShow.LogShow("当前数据项条件解析错误，错误信息：" + ef.ToString());
                                }
                            }
                            DataModel dataModelOpSging = new DataModel();
                            if (determine)
                            {
                                #region TODO:ZSW 标识优选旧逻辑
                                //if (isIdentifierOpt == true)
                                //{
                                //    Dictionary<string, string> sginDic = new Dictionary<string, string>();
                                //    foreach (var element in xmllableCofig.SignnodeList.NodeList)
                                //    {
                                //        if (dataModelAsisNode.AttributesList.FirstOrDefault(a => a.Name == element.Code) != null)
                                //        {
                                //            string elementvalue = dataModelAsisNode.AttributesList.FirstOrDefault(a => a.Name == element.Code).sourceList.FirstOrDefault(a => a.IsCheck == "1").SaveValue;
                                //            dataContext.InteractiveShow.LogShow("优选标识：" + element.Code + "进入标识优选值：" + elementvalue);
                                //            sginDic.Add(element.Code, elementvalue);
                                //        }
                                //        else
                                //        {
                                //            sginDic.Add(element.Code, null);
                                //        }
                                //    }
                                //    List<DataModel> dataSingList = new List<DataModel>();
                                //    if (dataModelListOP.FirstOrDefault(a => a.XmlPath == xmllableCofig.Xmlpath) != null)
                                //    {
                                //        dataSingList = dataModelListOP.Where(a => a.XmlPath == xmllableCofig.Xmlpath).ToList();
                                //        foreach (var dic in sginDic)
                                //        {
                                //            if (dic.Value == null)
                                //            {
                                //                if (dataSingList.FirstOrDefault(a => a.AttributesList.FirstOrDefault(b => b.Name == dic.Key) == null) != null)
                                //                {
                                //                    dataSingList = dataModelListOP.Where(a => a.XmlPath == xmllableCofig.Xmlpath && a.AttributesList.FirstOrDefault(b => b.Name == dic.Key) == null).ToList();
                                //                }
                                //                else
                                //                {
                                //                    dataSingList = new List<DataModel>();
                                //                }

                                //            }
                                //            else
                                //            {
                                //                if (dataModelListOP.FirstOrDefault(a => a.AttributesList.FirstOrDefault(b => b.Name == dic.Key &&
                                //                b.sourceList.FirstOrDefault(s => s.IsCheck == "1" && s.SaveValue == dic.Value) != null) != null) != null)
                                //                {
                                //                    dataSingList = dataSingList.Where(a => a.AttributesList.FirstOrDefault(b => b.Name == dic.Key &&
                                //                  b.sourceList.FirstOrDefault(s => s.IsCheck == "1" && s.SaveValue == dic.Value) != null) != null).ToList();
                                //                }
                                //                else
                                //                {
                                //                    dataSingList = new List<DataModel>();
                                //                }
                                //            }

                                //        }
                                //        dataContext.InteractiveShow.LogShow("标识查询结果：" + JsonConvert.SerializeObject(dataSingList));
                                //        if (dataSingList != null && dataSingList.Count > 0)
                                //        {
                                //            dataModelOpSging = dataSingList[0];
                                //            if (dataModelOpSging != null)
                                //            {
                                //                dataContext.InteractiveShow.LogShow("进入标识查询成功!");
                                //                dataModelListOP = SubordinateDataModelList(dataModelsOPList, dataModelOpSging);
                                //                List<DataModel> parentNodeModel = ParendNodeDataModelList(dataModelsOPList, dataModelOpSging);
                                //                dataModelListOP.AddRange(parentNodeModel);

                                //            }
                                //        }
                                //    }

                                //}
                                //else
                                //{
                                //    dataModelOpSging = dataModelListOP.FirstOrDefault(a => a.XmlPath == xmllableCofig.Xmlpath && a.State != "2");
                                //}
                                #endregion
                                bool isOptimize = true;
                                if (isIdentifierOpt == true)
                                {
                                    isOptimize = false;
                                    Dictionary<string, string> sginDic = new Dictionary<string, string>();
                                    foreach (var element in xmllableCofig.SignnodeList.NodeList)
                                    {
                                        if (dataModelAsisNode.AttributesList.FirstOrDefault(a => a.Name == element.Code) != null)
                                        {
                                            string elementvalue = dataModelAsisNode.AttributesList.FirstOrDefault(a => a.Name == element.Code).sourceList.FirstOrDefault(a => a.IsCheck == "1").SaveValue;
                                            dataContext.InteractiveShow.LogShow("优选标识：" + element.Code + "进入标识优选值：" + elementvalue);
                                            sginDic.Add(element.Code, elementvalue);
                                            isOptimize = true;
                                        }
                                        else
                                        {
                                            sginDic.Add(element.Code, null);
                                        }
                                    }
                                    List<DataModel> dataSingList = new List<DataModel>();
                                    if (dataModelListOP.FirstOrDefault(a => a.XmlPath == xmllableCofig.Xmlpath) != null)
                                    {
                                        dataSingList = dataModelListOP.Where(a => a.XmlPath == xmllableCofig.Xmlpath).ToList();
                                        /*
                                         是否相同节点数据
                                        只要标识中有一项值相同即为相同节点
                                         */
                                        bool isSameData = false;
                                        foreach (var dic in sginDic)
                                        {
                                            if (!string.IsNullOrWhiteSpace(dic.Value))
                                            {
                                                try
                                                {
                                                    if (dataModelListOP.FirstOrDefault(a => a.AttributesList.FirstOrDefault(b => b.Name == dic.Key &&
                                                b.sourceList.FirstOrDefault(s => s.IsCheck == "1" && s.SaveValue == dic.Value) != null) != null) != null)
                                                    {
                                                        dataSingList = dataSingList.Where(a => a.AttributesList.FirstOrDefault(b => b.Name == dic.Key &&
                                                      b.sourceList.FirstOrDefault(s => s.IsCheck == "1" && s.SaveValue == dic.Value) != null) != null).ToList();
                                                    }
                                                    else
                                                    {
                                                        dataSingList = new List<DataModel>();
                                                    }
                                                }
                                                catch
                                                {
                                                    dataSingList = new List<DataModel>();
                                                }

                                            }
                                        }

                                        dataContext.InteractiveShow.LogShow("标识查询结果：" + JsonConvert.SerializeObject(dataSingList));
                                        if (sginDic.Count == 0)
                                        {
                                            dataSingList = new List<DataModel>();
                                            isOptimize = false;
                                        }
                                        if (dataSingList != null && dataSingList.Count > 0)
                                        {
                                            dataModelOpSging = dataSingList[0];
                                            if (dataModelOpSging != null)
                                            {
                                                dataContext.InteractiveShow.LogShow("进入标识查询成功!");
                                                dataModelListOP = SubordinateDataModelList(dataModelsOPList, dataModelOpSging);
                                                if (dataModelOpSging.sourceData.sourceList.FirstOrDefault(a => a.SourceCode.ToLower() == dataContext.DataLayerAns.SourceCode.ToLower()) != null)
                                                {
                                                    dataModelOpSging.sourceData.sourceList.FirstOrDefault(a => a.SourceCode.ToLower() == dataContext.DataLayerAns.SourceCode.ToLower()).AnalysisStatus = "1";
                                                }
                                                 List<DataModel> parentNodeModel = ParendNodeDataModelList(dataModelsOPList, dataModelOpSging);
                                                foreach (var items in parentNodeModel)
                                                {
                                                    if (items.sourceData.sourceList.FirstOrDefault(a => a.SourceCode.ToLower() == dataContext.DataLayerAns.SourceCode.ToLower())!=null)
                                                    {
                                                        items.sourceData.sourceList.FirstOrDefault(a => a.SourceCode.ToLower() == dataContext.DataLayerAns.SourceCode.ToLower()).AnalysisStatus = "1";
                                                    }
                                                    
                                                }
                                                dataModelListOP.AddRange(parentNodeModel);

                                            }
                                        }
                                    }
                                    else
                                    {
                                        isOptimize = true;
                                    }

                                }
                                else
                                {
                                    dataModelOpSging = dataModelListOP.FirstOrDefault(a => a.XmlPath == xmllableCofig.Xmlpath && a.State != "2" && a.sourceData.sourceList.Any(x=>x.IsCheck=="1"));
                                }
                                dataContext.InteractiveShow.LogShow("旧当前节点：" + JsonConvert.SerializeObject(dataModelAsisNode));

                                dataContext.InteractiveShow.LogShow("旧优选结果节点：" + JsonConvert.SerializeObject(dataModelOpSging));
                                if (isSingleSourceOpt == true)
                                    xmllableCofig.Type = "b";
                                if (isOptimize == true)
                                {
                                    OptimizationData(dataModelAsisNode, dataModelOpSging, xmllableCofig, dataModelListOP, dataModelAsisList, OptimizeElement.Sourcedatadefine);
                                }
                                xmllableCofig.Type = oldConfigType;

                            }
                            if (dataModelOpSging != null && dataModelOpSging.sourceData != null)
                            {
                                CaseElmentOptimization(dataModelAsisList, dataModelAsisNode.ID, dataModelListOP, XmllableList);
                            }

                            foreach (DataModel opModel in dataModelListOP)
                            {
                                if (dataModelsOPList.FirstOrDefault(a => a.ID == opModel.ID && a.State == opModel.State) != null)
                                {
                                    DataModel model = dataModelsOPList.FirstOrDefault(a => a.ID == opModel.ID);
                                    model = opModel;
                                }
                                else
                                {
                                    dataModelsOPList.Add(opModel);
                                }
                            }
                        }
                        else
                        {
                            if (dataModelAsisNode.XmlPath.IndexOf("案由要素/事实要素/主张方") == -1 && dataModelAsisNode.XmlPath.IndexOf("案由要素/诉请要素/主张方") == -1)
                            {
                                DataModel dataModelOpSging = dataModelListOP.FirstOrDefault(a => a.XmlPath == dataModelAsisNode.XmlPath && a.State != "2");
                                if (dataModelOpSging == null)
                                {
                                    //获取上级节点信息
                                    string parentxml = "";
                                    List<string> pathlist = dataModelAsisNode.XmlPath.Split('/').ToList();
                                    pathlist.RemoveAt(pathlist.Count - 1);
                                    parentxml = string.Join("/", pathlist);
                                    try
                                    {
                                        CaseNodeUpdate(dataModelListOP, parentxml);
                                    }
                                    catch (Exception)
                                    {
                                    }

                                    DataModel nodeParent = dataModelListOP.FirstOrDefault(a => a.XmlPath == parentxml && a.State != "2");
                                    if (nodeParent != null)
                                    {
                                        string message = JsonConvert.SerializeObject(dataModelAsisNode);
                                        DataModel dataModelAddNode = JsonConvert.DeserializeObject<DataModel>(message);
                                        dataModelAddNode.ParentId = nodeParent.ID;
                                        dataModelListOP.Add(dataModelAddNode);
                                        dataModelsOPList.Add(dataModelAddNode);
                                    }
                                }
                                else
                                {
                                    try
                                    {
                                        List<DataModel> opList = dataModelListOP.Where(a => a.XmlPath == dataModelAsisNode.XmlPath && a.State != "2").ToList();
                                        if (opList.Count > 0)
                                        {
                                            if (!ISsameNode(opList, dataModelAsisNode))
                                            {
                                                //不存在该节点
                                                string parentxml = "";
                                                List<string> pathlist = dataModelAsisNode.XmlPath.Split('/').ToList();
                                                pathlist.RemoveAt(pathlist.Count - 1);
                                                parentxml = string.Join("/", pathlist);
                                                if (string.IsNullOrEmpty(parentxml))
                                                {
                                                    parentxml = dataModelAsisNode.XmlPath;
                                                }
                                                else
                                                {
                                                    CaseNodeUpdate(dataModelListOP, parentxml);
                                                }
                                                DataModel nodeParent = dataModelListOP.FirstOrDefault(a => a.XmlPath == parentxml && a.State != "2");
                                                string message = JsonConvert.SerializeObject(dataModelAsisNode);
                                                DataModel dataModelAddNode = JsonConvert.DeserializeObject<DataModel>(message);
                                                dataModelAddNode.ParentId = nodeParent.ID;
                                                dataModelListOP.Add(dataModelAddNode);
                                            }
                                        }
                                    }
                                    catch (Exception ex)
                                    {

                                        dataContext.InteractiveShow.LogShow("节点添加失败:" + dataModelAsisNode.XmlPath);
                                    }

                                }
                                CaseElmentOptimization(dataModelAsisList, dataModelAsisNode.ID, dataModelsOPList, XmllableList);
                            }
                            else
                            {
                                DataModel dataModelOpSging = dataModelListOP.FirstOrDefault(a => a.XmlPath == dataModelAsisNode.XmlPath && a.State != "2");
                                if (dataModelOpSging != null)
                                {
                                    dataModelOpSging.sourceData.sourceList.FirstOrDefault(a => a.IsCheck == "1").AnalysisStatus = "1";
                                }
                            }
                        }
                        #endregion
                    }
                }
            }
        }

        /// <summary>
        /// 将案由要素嵌入案件要素中。
        /// </summary>
        /// <param name="caseElmentdataModelList"></param>
        /// <param name="dicCauseElementdataModelList"></param>
        private void CaseElementListByCauseElmentList(List<DataModel> caseElmentdataModelList, Dictionary<string, List<DataModel>> dicCauseElementdataModelList)
        {
            DOCLocationModel locationModel = locationModelList.FirstOrDefault(x => x.DocType.ToLower() == dataContext.DataLayerAns.SourceCode.ToLower());
            if (locationModel != null && dicCauseElementdataModelList != null && dicCauseElementdataModelList.Count > 0 && caseElmentdataModelList?.Count > 0)
            {
                string path = locationModel.EelementPaht;
                //案件信息要素中心/仲裁/审理/案件审理阶段/详情[@阶段='a255']/案由信息/详情[@案由ID='{causecode}']/分人员要素
                if (!string.IsNullOrWhiteSpace(path))
                    path = path.Replace("[@案由ID='{causecode}']", "");
                if (caseElmentdataModelList.FirstOrDefault(a => a.XmlPath == path + "/案由要素") != null)
                {
                    List<DataModel> dataRomveList = caseElmentdataModelList.Where(a => a.XmlPath == path + "/案由要素").ToList();
                    //删除节点
                    foreach (DataModel dataRomve in dataRomveList)
                    {
                        caseElmentdataModelList.Remove(dataRomve);
                    }
                }
                dataContext.DataLayerOpt.ElementOptimizationResults = JsonConvert.DeserializeObject<Dictionary<string, List<DataModel>>>(JsonConvert.SerializeObject(dicCauseElementdataModelList));
                Dictionary<string, List<DataModel>> dicCauseEntityXmlModelList = new Dictionary<string, List<DataModel>>();
                foreach (var dicCauseModel in dicCauseElementdataModelList)
                {
                    
                    if (locationModel.EelementPaht.IndexOf("{causecode}") > -1)
                    {
                        if (dataContext.DataLayerAns.ExtractCaseCausesList!=null && dataContext.DataLayerAns.ExtractCaseCausesList.Count>0)
                        {
                            path = locationModel.EelementPaht.Replace("{causecode}", dataContext.DataLayerAns.ExtractCaseCausesList.FirstOrDefault(a => a.AllParentId.Contains(dicCauseModel.Key)).CC_ID);
                        }
                        else
                        {
                            path = locationModel.EelementPaht.Replace("{causecode}", dicCauseModel.Key);
                        }
                        
                    }
                    else
                    {
                        path = locationModel.EelementPaht.Replace(@"违法行为涉及领域/合并后要素", @"违法行为涉及领域[@领域ID='" + dicCauseModel.Key + "']/合并后要素").Replace(@"案由信息/详情", @"案由信息/详情[@案由ID='" + dicCauseModel.Key + "']");
                    }


                    DataModel dataModelCause = caseElmentdataModelList.FirstOrDefault(a => a.XmlPath == path);
                    if (dataModelCause == null)
                    {
                        base.CaseNodeUpdate(caseElmentdataModelList, path);
                        dataModelCause = XmlUtility.ConditionFirstOrDefaultDataModel(caseElmentdataModelList, "", path);
                    }
                    if (dataModelCause != null)
                    {
                        base.DelectNodeByDataModel(dataModelCause.ID, caseElmentdataModelList);
                    }
                    XmlDocument xml111 = XmlUtility.DataModelByXml(caseElmentdataModelList);
                    base.RestructureElment(dicCauseModel.Value, dicCauseModel.Key, dicCauseModel.Key);
                    DataModel dataModelCauseName = new DataModel();
                    dataModelCauseName.ID = Snowflake.Instance().GetId().ToString();
                    dataModelCauseName.XmlPath = path + "/案由要素";
                    dataModelCauseName.sourceData = new SourceData();
                    dataModelCauseName.CauseType = "1";
                    dataModelCauseName.ParentId = dataModelCause?.ID;
                    dataModelCauseName.sourceData.sourceList = new List<Source>();
                    Source source = new Source();
                    source.SourceCode = dataContext.DataCommon.SourceCode;
                    source.IsCheck = "1";
                    dataModelCauseName.sourceData.sourceList.Add(source);
                    if (dataModelCauseName.AttributesList == null)
                    {
                        dataModelCauseName.AttributesList = new List<AttributeInfo>();
                    }
                    AttributeInfo causeNameAttr = new AttributeInfo();
                    causeNameAttr.Name = "案由名称";
                    Source causeNameSource = new Source();
                    causeNameSource.IsCheck = "1";
                    causeNameSource.SourceCode = dataContext.DataCommon.SourceCode;
                    causeNameSource.SaveValue = dataContext.DataCommon.ExtractCaseCausesList.FirstOrDefault(x=>x.AllParentId.Contains(dicCauseModel.Key))?.CC_Name;
                    causeNameAttr.sourceList = new List<Source>();
                    causeNameAttr.sourceList.Add(causeNameSource);
                    dataModelCauseName.AttributesList.Add(causeNameAttr);

                    AttributeInfo causeIdAttr = new AttributeInfo();
                    causeIdAttr.Name = "案由ID";
                    Source causeIdSource = new Source();
                    causeIdSource.IsCheck = "1";
                    causeIdSource.SourceCode = dataContext.DataCommon.SourceCode;
                    causeIdSource.SaveValue = dataContext.DataCommon.ExtractCaseCausesList.FirstOrDefault(x => x.AllParentId.Contains(dicCauseModel.Key))?.CC_ID;
                    causeIdAttr.sourceList = new List<Source>();
                    causeIdAttr.sourceList.Add(causeIdSource);
                    dataModelCauseName.AttributesList.Add(causeIdAttr);

                    caseElmentdataModelList.Add(dataModelCauseName);
                    //保存案由要素优选结果
                    List<DataModel> dataModelCauseModleList = dicCauseModel.Value.Where(a => a.ParentId == dicCauseModel.Key).ToList();
                    dataModelCauseModleList = dicCauseModel.Value.Where(a => a.XmlPath.Split('/')[a.XmlPath.Split('/').Length - 1] == "诉请要素" || a.XmlPath.Split('/')[a.XmlPath.Split('/').Length - 1] == "事实要素" || a.XmlPath.Split('/')[a.XmlPath.Split('/').Length - 1] == "结果要素").ToList();
                    //案由要素优选结果
                    DataSoursModel causeDataSoursModel = new DataSoursModel();
                    causeDataSoursModel.dataModelList = new List<DataModel>();
                    DataModel dataModelsour = JsonConvert.DeserializeObject<DataModel>(JsonConvert.SerializeObject(dataModelCauseName));
                    dataModelsour.ParentId = "";
                    causeDataSoursModel.dataModelList.Add(dataModelsour);

                    #region TODO:ZSW 证据与事实要素关系建立
                    if (base.dataContext.DataLayerOpt.EvidenceFactRelations == null)
                        base.dataContext.DataLayerOpt.EvidenceFactRelations = new List<EvidenceFactRelationModel>();
                    List<EvidenceFactRelationModel> relList = new List<EvidenceFactRelationModel>();
                    if (dataContext.DataLayerOpt.EvidenceFactRelations != null && dataContext.DataLayerOpt.EvidenceFactRelations.Any())
                    {
                        relList = dataContext.DataLayerOpt.EvidenceFactRelations;
                    }
                    #endregion

                    foreach (DataModel causeModel in dataModelCauseModleList)
                    {
                        if (dicCauseModel.Value.FirstOrDefault(a => a.ParentId == causeModel.ID && a.XmlPath.IndexOf("主张方") > -1) != null)
                        {
                            List<EvidenctNodeRecord> nodeRecord = new List<EvidenctNodeRecord>();
                            List<DataModel> dataModelElment = SubordinateDataModelList(dicCauseModel.Value, causeModel);
                            dataModelElment = dataModelElment.Select(item => item.Clone()).ToList();
                            #region TODO:ZSW 证据与事实要素关系建立
                            var evidModels = dataModelElment.Where(x => x.sourceData != null && x.sourceData.sourceList != null && x.sourceData.sourceList.Any(s=>s.IsCheck=="1")).ToList();
                            if (evidModels != null && evidModels.Any())
                            {
                                foreach (var evidModel in evidModels)
                                {
                                    var evidSourceData = evidModel.sourceData.sourceList.FirstOrDefault(x => x.SourceID == dataContext.DataLayerAns.SF_ID);
                                    if (evidSourceData != null)
                                    {
                                        if (!string.IsNullOrWhiteSpace(evidSourceData.SourceID) && !string.IsNullOrWhiteSpace(evidSourceData.SourceNodeId))
                                        {
                                            string evidsfid = evidSourceData.SourceID;
                                            string evidModelid = evidSourceData.SourceNodeId;
                                            EvidenceFactRelationModel relation = new EvidenceFactRelationModel();
                                            relation.EvidenceFileId = evidsfid;
                                            relation.FactElenemtId = evidModel.ID;
                                            relation.ElementType = "1";
                                            relation.EvidenceElementId = evidModelid;
                                            relation.Xpath = evidModel.XmlPath;
                                            if (evidModel.XmlPath != "案由要素/事实要素" && !evidModel.XmlPath.Contains("事实要素/主张方"))
                                                relList.Add(relation);
                                        }
                                    }
                                }
                                //去除证据重置记录中不是参与分人员要素需要保存的并且记录类型是证据要素的数据
                                if (!string.IsNullOrWhiteSpace(dataContext.DataLayerAns.SF_ID))
                                {
                                    string sfid = dataContext.DataLayerAns.SF_ID;
                                    if (nodeRecord != null && nodeRecord.Any(x => x.EvidenctFileId == sfid))
                                    {
                                        var factRecordIds = nodeRecord.Where(x => x.EvidenctFileId == sfid)
                                                                    .Select(x => x.ResetBeforeId).ToList();
                                        if (factRecordIds != null && factRecordIds.Any())
                                        {
                                            var evidRecords = dataContext.DataLayerOpt.EvidenctNodeRecords.Where(x => x.RecoredType == "1" && x.EvidenctFileId == sfid);
                                            if (evidRecords != null && evidRecords.Any())
                                            {
                                                var delRecords = evidRecords.Where(x => !factRecordIds.Contains(x.ResetAfterId)).ToList();
                                                if (delRecords != null && delRecords.Any())
                                                {
                                                    foreach (var delRecord in delRecords)
                                                    {
                                                        dataContext.DataLayerOpt.EvidenctNodeRecords.Remove(delRecord);
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                            DataModelIDByReset(dataModelElment, causeModel.ParentId, dataModelCauseName.ID);
                            if (relList != null && relList.Any())
                            {
                                foreach (var relItem in relList)
                                {
                                    //获取证据数据的节点ID
                                    var evidDataId = relItem.EvidenceElementId;
                                    var factData = dataModelElment.FirstOrDefault(x => x.XmlPath == relItem.Xpath && x.sourceData.sourceList.Any(s => s.SourceNodeId == evidDataId));
                                    if (factData != null)
                                        relItem.FactElenemtId = factData.ID;
                                }
                            }
                            #endregion
                            causeDataSoursModel.dataModelList.AddRange(dataModelElment.Select(item => item.Clone()));
                            caseElmentdataModelList.AddRange(dataModelElment);
                            XmlDocument xml=  XmlUtility.DataModelByXml(caseElmentdataModelList);
                        }
                        else
                        {
                            causeModel.ParentId = dicCauseModel.Key + "_1";
                        }
                    }
                    dataContext.DataLayerOpt.EvidenceFactRelations = relList;
                    dicCauseEntityXmlModelList.Add(dicCauseModel.Key, causeDataSoursModel.dataModelList);

                }
                dataContext.DataLayerOpt.ElementOptimizationResults = dicCauseEntityXmlModelList;
                dataContext.DataLayerOpt.OptimizeCauseEntityXml = null;
                dataContext.DataLayerOpt.SourdatModleList = caseElmentdataModelList;
                dataContext.DataLayerOpt.OptimizationXml = XmlUtility.DataModelByXml(caseElmentdataModelList);
            }
        }


    }
}
